<template>
  <div class="Reg-box">
    <!-- 注册顶部 -->
    <van-nav-bar title="注册" left-text="返回" left-arrow @click-left="GoBack">
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <!-- 提交 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="手机/用户名"
        label="手机/用户名"
        placeholder="手机/用户名"
        :rules="[{ required: true, message: '请填写手机/用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px" class="Login-sumbit">
        <van-button round block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  name: "Reg",
  data() {
    return {
      username: "",
      password: "123456",
      RandomCode: "",
      msg: "",
    };
  },
  created() {
    this.getRandomCode();
  },
  methods: {
    GoBack() {
      this.$router.go(-1);
    },
    onSubmit() {
      this.service ({
        method: "post",
        url: "/user/dosendmsgcode",
        data:`tel=${this.username}`
      })
      .then(res=>{
        if (res.data.code == 200) {
          this.service({
          method:'post',
          url:"/user/dofinishregister",
          data:`tel=${this.username}&password=${this.password}`
        })
        .then((res) => {
          if (res.data.code == 200) {
              console.log(res);
              setTimeout (()=>{
                this.$router.push("/Login");
              }, 1000)
              this.$toast.success('注册成功！请登录');
          } else {
            alert('注册失败！');
          }
        })
        }
      })
    },
    // 产生随机验证码
    getRandomCode() {
      let str = "";
      for (let i = 0; i < 4; i++) {
        str += parseInt(Math.random() * 10);
      }
      this.RandomCode = str;
    },     
    },
};
</script>

<style scoped>
    p {
        text-align: center;
    }
</style>